const fs =require ('fs');

var order=[];

function readOrder(target){
    fs.readFile('./order.json','utf-8',(err,data)=>{
        target=JSON.parse(data);
        console.log(target);
    });

}

 function addOrder(k,v){
    fs.readFile('./order.json','utf-8',(err,data)=>{
        target=JSON.parse(data);
        console.log('添加数据之前：')
        console.log(orders);
              var o={
            gId:k,
            goodName:v.goodName,
            gPrice:v.gPrice
        }
        orders.push(o);
        fs.writeFile('./order.json',JSON.stringify(orders),(err,bytes,str)=>{
                    if(err){
                     
                        throw err;
                        return false;
                    }
                    console.log('添加数据成功！共写入'+bytes +'字节。');
                });
    });

    //  fs.open ('./order.json','a+',(err,fd)=>{
    //     if(err){
    //         throw err;
    //         return false;
    //     }
    //     var o={
    //         gId:k,
    //         goodName:v.goodName,
    //         gPrice:v.gPrice
    //     }
    //     fs.write(fd,JSON.stringify(o),(err,bytes,str)=>{
    //         if(err){
    //             fs.close(fd);
    //             throw err;
    //             return false;
    //         }
    //         console.log('添加数据成功！共写入'+bytes +'字节。');
    //     });
    //  });
 }

 function modifyOrder(k,v){

        fs.readFile('./order.json','utf-8',(err,data)=>{
            target=JSON.parse(data);
            console.log('添加数据之前：')
            console.log(orders);
            for(var d of orders){
                if(d.gId==k){
                    d.goodName=v.goodName;
                    d.gPrice =v.gPrice;
                    break;
                }
            }
            fs.writeFile('./order.json',JSON.stringify(orders),(err,bytes,str)=>{
                        if(err){
                         
                            throw err;
                            return false;
                        }
                        console.log('添加数据成功！共写入'+bytes +'字节。');
                    });
        });
 }
 function delOrder(k){
    
    fs.readFile('./order.json','utf-8',(err,data)=>{
        target=JSON.parse(data);
        console.log('添加数据之前：')
        console.log(orders);
      for (var i=0;i<orders.length;i++){
        if(orders[i].gId==k){
            pos=i;break;
        }
      }
      orders.splice(pos,1);
        fs.writeFile('./order.json',JSON.stringify(orders),(err,bytes,str)=>{
                    if(err){
                     
                        throw err;
                        return false;
                    }
                    console.log('添加数据成功！共写入'+bytes +'字节。');
                });
    });
 }

// readOrder(orders);
// console.log(orders);
addOrder('003',{
    goodName:'矿泉水',
    gPrice:2
});